/**
 *
 */
package com.pocketsweet;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.PushService;
import com.easemob.EMCallBack;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.pocketsweet.chatui.MLHXSDKHelper;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLArticleComment;
import com.pocketsweet.model.MLArticleLike;
import com.pocketsweet.model.MLAuthentication;
import com.pocketsweet.model.MLCallRecord;
import com.pocketsweet.model.MLConsumeRecord;
import com.pocketsweet.model.MLCustomizationRecord;
import com.pocketsweet.model.MLDate;
import com.pocketsweet.model.MLException;
import com.pocketsweet.model.MLFeedback;
import com.pocketsweet.model.MLFriendApply;
import com.pocketsweet.model.MLGallery;
import com.pocketsweet.model.MLGift;
import com.pocketsweet.model.MLGiftRecord;
import com.pocketsweet.model.MLInfoChangeNotify;
import com.pocketsweet.model.MLLovers;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLPaidVoip;
import com.pocketsweet.model.MLRecommendUser;
import com.pocketsweet.model.MLReportRecord;
import com.pocketsweet.model.MLShare;
import com.pocketsweet.model.MLSignRecord;
import com.pocketsweet.model.MLTask;
import com.pocketsweet.model.MLTestOrder;
import com.pocketsweet.model.MLTopic;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLUserCount;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.model.MLVoice;
import com.pocketsweet.model.MLWithdraw;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.Splash;
import com.pocketsweet.utils.ACache;
import com.pocketsweet.utils.Logger;
import com.pocketsweet.utils.PhotoUtil;
import com.pocketsweet.utils.ToolKits;

/**
 * @author hantian
 */
public class MLApplication extends Application implements
        Thread.UncaughtExceptionHandler {
    // 本地存储所用的数据库
    public static final String DB_NAME = "molian.db3";
    public static final int DB_VER = 2;

    public final String PREF_USERNAME = "username";
    ArrayList<Activity> activityList = new ArrayList<Activity>();

    /**
     * 当前用户nickname,为了苹果推送不是userid而是昵称
     */
    public static String currentUserNick = "";
    public static MLHXSDKHelper hxSDKHelper = new MLHXSDKHelper();

    public static Context mContext;
    public static ACache mCache;
    private static MLApplication _instance;

    public static boolean debug = true;
    public static boolean isLogin = false;

    // 记录实习恋人的位置
    public static int mPosition;
    public static int lvChildTop;
    public static int chooseSex = -1;

    public boolean needUpdateUserInfo = false;
    private MLUser inforProvider;
    private List<MLUser> userList;
    private static List<MLUser> testUserList;
    private List<MLArticle> mArticle;

    public boolean getIsLogin() {
        return isLogin;
    }

    public void setIsLogin(boolean isLogin) {
        MLApplication.isLogin = isLogin;
    }

    public List<MLUser> getTestUserList() {
        return testUserList;
    }

    public void setTestUserList(List<MLUser> testUserList) {
        MLApplication.testUserList = testUserList;
    }

    public List<MLUser> getUserList() {
        return userList;
    }

    public void setUserList(List<MLUser> userList) {
        this.userList = userList;
    }

    public List<MLArticle> getmArticle() {
        return mArticle;
    }

    public void setmArticle(List<MLArticle> mArticle) {
        this.mArticle = mArticle;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        _instance = this;
        MLContext.init(this);
        UserService.init();
        // Log.v("molian", ToolKits.getCurProcessName(mContext));
        AVOSCloudInit();
        // 环信初始化
        hxSDKHelper.onInit(this);
        checkMolianFloders();
        initImageLoader(this);
        // MLcache
        MLCache.init(this);
        // MLOrderTimer
        MLOrderTimer.init();
    }

    public static Context getContext() {
        return mContext;
    }

    public static ACache getCache() {
        return mCache;
    }

    public static MLApplication getInstance() {
        return _instance;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    private void AVOSCloudInit() {
        // 使用中国的服务器
        AVOSCloud.useAVCloudCN();
        // 初始化应用 Id 和 应用 Key，您可以在应用设置菜单里找到这些信息
        AVOSCloud.initialize(this, C.AV_APP_KEY, C.AV_APP_SECRET);
        // 启用崩溃错误报告
        AVAnalytics.enableCrashReport(this, true);
        // 设置成使用正式代码
        AVCloud.setProductionMode(true);

        PushService.setDefaultPushCallback(this, Splash.class);
        // 默认订阅一个频道
        PushService.subscribe(this, "public", Splash.class);
        PushService.subscribe(this, "android", Splash.class);
        AVOSCloud.setDebugLogEnabled(debug);
        if (debug) {
            Logger.level = Logger.VERBOSE;
        } else {
            Logger.level = Logger.NONE;
        }

        // 注册子类
        AVObject.registerSubclass(MLGallery.class);
        AVObject.registerSubclass(MLUser.class);
        AVUser.alwaysUseSubUserClass(MLUser.class);
        AVObject.registerSubclass(MLWithdraw.class);
        AVObject.registerSubclass(MLFeedback.class);
        AVObject.registerSubclass(MLReportRecord.class);
        AVObject.registerSubclass(MLArticleComment.class);
        AVObject.registerSubclass(MLArticle.class);
        AVObject.registerSubclass(MLDate.class);
        AVObject.registerSubclass(MLUserLike.class);
        AVObject.registerSubclass(MLArticleLike.class);
        AVObject.registerSubclass(MLPaidVoip.class);
        AVObject.registerSubclass(MLRecommendUser.class);
        AVObject.registerSubclass(MLShare.class);
        AVObject.registerSubclass(MLTask.class);
        AVObject.registerSubclass(MLTopic.class);
        AVObject.registerSubclass(MLUserCount.class);
        AVObject.registerSubclass(MLFriendApply.class);
        AVObject.registerSubclass(MLVoice.class);
        AVObject.registerSubclass(MLCallRecord.class);
        AVObject.registerSubclass(MLConsumeRecord.class);
        AVObject.registerSubclass(MLLovers.class);
        AVObject.registerSubclass(MLAuthentication.class);
        AVObject.registerSubclass(MLCustomizationRecord.class);
        AVObject.registerSubclass(MLOrder.class);
        AVObject.registerSubclass(MLTestOrder.class);
        AVObject.registerSubclass(MLInfoChangeNotify.class);
        AVObject.registerSubclass(MLException.class);
        AVObject.registerSubclass(MLGift.class);
        AVObject.registerSubclass(MLGiftRecord.class);
        AVObject.registerSubclass(MLSignRecord.class);

    }

    /**
     * 初始化imageloader
     *
     * @param context
     */
    public static void initImageLoader(Context context) {
        File cacheDir = StorageUtils.getOwnCacheDirectory(context,
                "pocketsweet/Cache");
        ImageLoaderConfiguration config = PhotoUtil.getImageLoaderConfig(
                context, cacheDir);
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

    /**
     * check molian floader
     */
    public static void checkMolianFloders() {
        if (!ToolKits.isSdCardMounted()) {
            Toast.makeText(MLApplication.getContext(),
                    R.string.sdcard_not_available, Toast.LENGTH_LONG).show();
            return;
        }
        File cache_file = new File(C.CACHE_FILE);
        if (!cache_file.exists()) {
            cache_file.mkdirs();
        }
    }

    /**
     * 获取当前登陆用户名
     *
     * @return
     */
    public String getUserName() {
        return hxSDKHelper.getHXId();
    }

    /**
     * 获取密码
     *
     * @return
     */
    public String getPassword() {
        return hxSDKHelper.getPassword();
    }

    /**
     * 设置用户名
     *
     * @param user
     */
    public void setUserName(String username) {
        hxSDKHelper.setHXId(username);
    }

    /**
     * 设置密码 下面的实例代码 只是demo，实际的应用中需要加password 加密后存入 preference 环信sdk
     * 内部的自动登录需要的密码，已经加密存储了
     *
     * @param pwd
     */
    public void setPassword(String pwd) {
        hxSDKHelper.setPassword(pwd);
    }

    /**
     * 退出登录,清空数据
     */
    public void logout(final EMCallBack emCallBack) {
        // 先调用sdk logout，在清理app中自己的数据
        hxSDKHelper.logout(emCallBack);
    }

    @Override
    public void uncaughtException(Thread arg0, Throwable arg1) {
        Intent intent = new Intent(getApplicationContext(), Splash.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, intent,
                Intent.FLAG_ACTIVITY_NEW_TASK);
        AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis(), restartIntent);
        finishActivity();


        // if (UserService.getCurrentUser() == null) {
        // System.exit(0);
        // Intent intent2 = new Intent(this, Splash.class);
        // intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        // | Intent.FLAG_ACTIVITY_NEW_TASK);
        // startActivity(intent2);
        // // Intent k = getBaseContext().getPackageManager()
        // // .getLaunchIntentForPackage(getBaseContext().getPackageName());
        // // k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // // startActivity(k);
        // }
    }

    public void removeActivity(Activity a) {
        activityList.remove(a);
    }

    public void addActivity(Activity a) {
        activityList.add(a);
    }

    public void finishActivity() {
        for (Activity activity : activityList) {
            if (activity != null) {
                activity.finish();
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());// 杀死应用
    }

    public boolean isHasActivity() {
        int len = activityList.size();
        if(len>=1){
            return true;
        }
        return false;

//        for (int i = 0; i < len; i++) {
//            if (i != (len - 1)) {
//                activity = activityList.get(0);
//                activity.finish();
//                return true;
//            }
//        }


//        for (Activity activity : activityList) {
//            if (activityList.size() > 1) {
//                activity = activityList.get(0);
//                activity.finish();
//            }
//        }
//        Activity activity;
//        if(activityList.size()>1){
//            activity=activityList.get(activityList.size()-1);
//            activity.finish();
//        }


//        Activity activity;
//        if(activityList.size()>1){
//            activity=activityList.get(0);
//            activity.finish();
//        }

//        for (Activity activity : activityList) {
//            if (activity != null && activity != activityList.get(0)) {
//                activity.finish();
//            }
//        }
    }
}
